{% extends "themes/" + sysSettings.systemTheme + "/layout.html" %}

{% block head %}
<title>{{sysSettings.siteName}} - {{channel.channelName}}</title>
<meta name="twitter:card" content="player" />
<meta property="og:site_name" content="{{sysSettings.siteName}}" />
<meta property="og:title" content="{{channel.channelName}}" />
<meta property="og:type" content="video.other" />
<meta property="og:url" content="{{request.url|normalize_url}}" />
<meta property="og:image" content="{{request.url_root|normalize_urlroot}}/images/{{channel.imageLocation}}" />
<meta property="og:description" content="{{channel.description}}" />
<meta property="og:video" content="{{request.url_root|normalize_urlroot}}{{streamURL}}" />
<meta property="og:video:type" content="application/x-mpegURL" />
<script type="text/javascript" src="/static/vendor/socketio/js/socket.io.js"></script>
<script type="text/javascript" src="/static/vendor/popper/js/popper.min.js"></script>
<link href="/static/vendor/videojs/css/video-js.css" rel="stylesheet">
<script src="/static/vendor/videojs/js/video.js"></script>

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">

{% endblock %}

{% block body %}
<div class="container-fluid">
     <div class="row">
         <div class="col-lg col-xs-12 col-sm-12">
              <div class="index-video-title ml-2 my-2">
                  <span class="float-left" id="channelName"><b>{{channel.channelName}}</b></span>
                  <span class="float-right mx-1">
                    {% if current_user.is_authenticated %}
                      <button id="chanSubStateButton" class="btn btn-sm {% if subState == True %} btn-success {% else %} btn-outline-success {% endif %}" onclick='toggleChannelSub("{{channel.id}}")'>{% if subState == True %}<i class="fas fa-star"></i><span class="d-none d-sm-none d-md-inline"> Unsubscribe</span>{% else %}<i class="far fa-star"></i><span class="d-none d-sm-none d-md-inline"> Subscribe</span>{% endif %}</button>
                    {% else %}
                      <button class="btn btn-sm btn-outline-secondary disabled" disabled><i class="far fa-star"></i><span class="d-none d-sm-none d-md-"> Subscribe</span></button>
                    {% endif %}
                  </span>
                  <span class="float-right mt-2">
                      <span id="liveIndicatorBadge" class="badge badge-secondary"><b><i class="fas fa-video-slash"></i><span class="d-none d-sm-none d-md-inline"> Offline</span></b></span>
                    {% if channel.protected and sysSettings.protectionEnabled %}
                      <span class="badge badge-warning float-right mr-1 align-bottom"><i class="fas fa-user-lock"></i><span class="d-none d-sm-none d-md-inline"> Protected</span></span>
                    {% endif %}
                  </span>
              </div>
         </div>
         <div class="col-lg-auto col-sm-12" style="width:475px;">
            <ul id="channelPlayerMenu" class="nav nav-pills nav-justified mx-2 mb-2">
                <li class="nav-item">
                    <a class="nav-link active" id="channel-tab" data-toggle="tab" href="#livechannel" role="tab" aria-controls="home" aria-selected="true"><b>Live</b></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="videos-tab" data-toggle="tab" href="#videoList" role="tab" aria-controls="profile" aria-selected="false"><b>Videos</b></a>
                </li>
                 <li class="nav-item">
                    <a class="nav-link" id="clips-tab" data-toggle="tab" href="#clipList" role="tab" aria-controls="profile" aria-selected="false"><b>Clips</b></a>
                </li>
              </ul>
         </div>
     </div>
    <div class="tab-content" id="tabList">
        <div class="tab-pane fade show active" id="livechannel" role="tabpanel" aria-labelledby="channel-tab">
        <div class="row">
            <div class="{% if channel.chatEnabled == True %}col-lg{% else %} col-12{% endif %} col-xs-12 col-sm-12" id="videoWindow">
                <div class="videoPanel">
                     <div class="player ml-2">
                         <div id="videoContainer">
                             <video id="video" class="shadow videoStream video-js vjs-big-play-centered" poster="/stream-thumb/{{channel.channelLoc}}.png" autoplay controls preload="auto" data-setup='{"fluid": true}'>
                                <p class="vjs-no-js">
                                  To view this video please enable JavaScript, and consider upgrading to a web browser that
                                  <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
                                </p>
                             </video>
                         </div>
                         <div id="offlineImage" style="display:none;">
                            <img class="videoStream shadow" {% if channel.offlineImageLocation != None %} src="/images/{{channel.offlineImageLocation}}" {% else %} src="/static/img/video-placeholder.jpg" {% endif %}>
                         </div>
                     </div>
                     <div class="row m-2">
                         <div class="video-buttons-row">
                             <span class="float-left">
                                  <button type="button" class="btn btn-primary shadow {% if channel.chatEnabled == False %}disabled{% endif %}" data-toggle="button" aria-pressed="false" autocomplete="off" onclick="toggleChat()">
                                    <i class="fas fa-comment"></i>
                                  </button>
                                  <button type="button" class="btn btn-primary shadow" data-toggle="modal" data-target="#shareModal">
                                    <i class="fas fa-share-alt"></i>
                                  </button>

                                  {% if channel.owningUser == current_user.id %}
                                  <button type="button" class="btn btn-primary shadow" data-toggle="modal" data-target="#editModal">
                                    <i class="fas fa-edit"></i>
                                  </button>
                                  {% endif %}
                             </span>
                             <span class="float-right">
                                  <i class="fas fa-users mx-2"></i> {{channel.views}}
                                  <i class="fas fa-eye mx-2"></i> <span id="currentViewers">{{channel.currentViewers}}</span>
                                  <button id="upvoteButton" type="button" class="btn btn-outline-success shadow ml-3" onclick="changeUpvote();" title="Upvote" {% if current_user.is_authenticated==false %} disabled aria-disabled="true"{% endif %}>
                                      <i id="upVoteIcon" class="far fa-thumbs-up"> <span id="totalUpvotes"></span></i>
                                  </button>
                              </span>
                          </div>
                     </div>
                     <div class="row m-2">
                        <div class="col-12 nopadding">
                            <div id="streamMetadataName" class="mr-5"><b><i class="fas fa-video"></i> {% if stream != None %} {{stream.streamName}} {% else %} No Stream {% endif %}</b></div>
                            <div id="streamMetadataTopic"><b><i class="fas fa-hashtag"></i><a href="/topic/{{stream.topic}}/">{% if stream != None %} {{stream.topic|get_topicName}} {% else %} {{channel.topic|get_topicName}} {% endif %}</a></b></div>
                        </div>
                     </div>
                     <div class="row m-2">
                        <div class="channeldescription">{% if channel.description != None %}<p>{{channel.description|markdown}}</p> {% else %}No Description Available {% endif %}</div>
                     </div>
                </div>
            </div>
            {% if channel.chatEnabled == True %}
            <div id="chatside" class="col-lg-auto col-xs-12 col-sm-12" >
                <div class="row ml-2 mr-1">
                    <div class="index-video-title mb-2"><b>Chat</b></div>
                    <div class="chatbox" id="chatBlock">
                          <div id="chat" class="chat"></div><br>
                          <input autocomplete="off" id="text" size="80" class="form-control shadow" {% if current_user.is_authenticated==false %} disabled placeholder="Login to Chat" {% else %} placeholder="Type Message Here..." {% endif %}><br>
                          <button type="button" id="userList" class="btn btn-primary shadow" data-html="true" data-toggle="popover" title="<b>User List</b>" data-content="" data-placement="right"><i class="fas fa-list"></i></button>
                          <a href="#" onClick="popoutChat();return false;" class="btn btn-primary shadow" title="Popout Chat"><i class="fas fa-external-link-alt"></i></a>
                          <span class="float-right"><button id="chatSubmit" class="btn btn-success shadow" onclick="sendChat();">Send</button></span>
                      </div>
                </div>
            </div>
            {% endif %}
         </div>
        </div>
        <div class="tab-pane fade" id="videoList" role="tabpanel" aria-labelledby="videos-tab">
            <div class="container-fluid p-2" id="index-videos-container">
                <div class="row">
                    <div id="recordedVideoList" class="col-lg col-xs-12 col-sm-12">
                        <div class="row mx-2">
                            <div class="col-12 col-md-10 col-lg-11">
                                <div class="index-video-title"><b>Videos</b></div>
                            </div>
                            <div class="col-12 col-md-2 col-lg-1">
                                <span class="dropdown">
                                    <button class="btn btn-secondary dropdown-toggle shadow" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                        <i class="fas fa-sort"></i> Sort
                                    </button>
                                    <div class="dropdown-menu shadow" aria-labelledby="dropdownMenuButton">
                                        <span class="sort dropdown-item" data-sort="name">Sort by Name</span>
                                        <span class="sort dropdown-item" data-sort="upvotes">Sort by Upvotes</span>
                                        <span class="sort dropdown-item" data-sort="views">Sort by Views</span>
                                        <span class="sort dropdown-item" data-sort="length">Sort by Length</span>
                                        <span class="sort dropdown-item" data-sort="date">Sort by Date</span>
                                    </div>
                                </span>
                            </div>
                        </div>
                        <ul class="itemList list d-flex flex-wrap justify-content-start">
                            {% for video in channel.recordedVideo|sort(attribute='videoDate', reverse=True)%}
                            {% if video.pending == False and video.published == True %}

                            <li class="displayCard mx-4 my-3">
                              <a href="/play/{{video.id}}">
                                <div class="displayCard-thumbnail zoom">
                                  <div class="video-badges">
                                    {% if channel.protected and sysSettings.protectionEnabled %}<span class="badge badge-warning mx-2"><i class="fas fa-user-lock"></i> Protected</span>{% endif %}
                                  </div>
                                  <img class="shadow lazy" src="/static/img/video-placeholder.jpg" data-src="/videos/{{video.thumbnailLocation}}" onerror="this.src='/static/img/video-placeholder.jpg';">
                                  <div class="displayCard-counts">
                                    <span class="displayCard-left align-left" style="color:white;">
                                      <span class="px-2 flex-fill upvotes"><i class="fas fa-thumbs-up"></i> <b>{{video.id|get_Video_Upvotes}}</b></span>
                                    </span>
                                    <span class="displayCard-right" style="float:right;color:white;">
                                      <span class="px-2 flex-fill views"><i class="fas fa-users"></i> <b>{{video.views}}</b></span>
                                      <span class="px-2 flex-fill length"><i class="fas fa-clock"></i> <b>{{video.length|hms_format}}</b></span>
                                    </span>
                                  </div>
                                </div>
                                <div class="card-data">
                                  <img class="rounded" src="/images/{{channel.owner.pictureLocation}}" onerror="this.src='/static/img/user2.png';">
                                  <div class="metadata">
                                    <div class="card-cut-text name ml-2"><b>{{video.channelName|limit_title}}</b></div>
                                    <div class="card-cut-text topic ml-2">{{video.topic|get_topicName}}</div>
                                    <span class="date" style="display:none;">{{video.videoDate|normalize_date}}</span>
                                  </div>
                                </div>
                              </a>
                            </li>
                            {% endif %}
                            {% endfor %}
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="tab-pane fade" id="clipList" role="tabpanel" aria-labelledby="clips-tab">
            <div class="row">
                <div id="clipsList" class="col-lg col-xs-12 col-sm-12">
                    <div class="row mx-2">
                        <div class="col-12 col-md-10 col-lg-11">
                            <div class="index-video-title"><b>Clips</b></div>
                        </div>
                        <div class="col-12 col-md-2 col-lg-1">
                            <span class="dropdown">
                                <button class="btn btn-secondary dropdown-toggle shadow" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <i class="fas fa-sort"></i> Sort
                                </button>
                                <div class="dropdown-menu shadow" aria-labelledby="dropdownMenuButton">
                                    <span class="sort dropdown-item" data-sort="name">Sort by Name</span>
                                    <span class="sort dropdown-item" data-sort="upvotes">Sort by Upvotes</span>
                                    <span class="sort dropdown-item" data-sort="views">Sort by Views</span>
                                    <span class="sort dropdown-item" data-sort="length">Sort by Length</span>
                                    <span class="sort dropdown-item" data-sort="date">Sort by Date</span>
                                </div>
                            </span>
                        </div>
                    </div>
                    <ul class="itemList list d-flex flex-wrap justify-content-start">
                        {% for clip in clipsList %}
                        <li class="displayCard mx-4 my-3">
                          <a href="/clip/{{clip.id}}">
                            <div class="displayCard-thumbnail zoom">
                              <div class="video-badges">
                                {% if channel.protected and sysSettings.protectionEnabled %}<span class="badge badge-warning mx-2"><i class="fas fa-user-lock"></i> Protected</span>{% endif %}
                              </div>
                              <img class="shadow lazy" {% if channel.protected and sysSettings.protectionEnabled %} src="/static/img/video-locked.jpg" onerror="this.src='/static/img/video-locked.jpg';" {% else %} src="/static/img/video-placeholder.jpg"
                                        onerror="this.src='/static/img/video-placeholder.jpg';" {% endif %} data-src="/videos/{{clip.thumbnailLocation}}">
                              <div class="displayCard-counts">
                                <span class="displayCard-left align-left" style="color:white;">
                                  <span class="px-2 flex-fill upvotes"><i class="fas fa-thumbs-up"></i> <b>{{clip.id|get_Clip_Upvotes}}</b></span>
                                </span>
                                <span class="displayCard-right" style="float:right;color:white;">
                                  <span class="px-2 flex-fill views"><i class="fas fa-users"></i> <b>{{clip.views}}</b></span>
                                  <span class="px-2 flex-fill length"><i class="fas fa-clock"></i> <b>{{clip.length|hms_format}}</b></span>
                                </span>
                              </div>
                            </div>
                            <div class="card-data">
                              <img class="rounded" src="/images/{{channel.owner.pictureLocation}}" onerror="this.src='/static/img/user2.png';">
                              <div class="metadata">
                                <div class="card-cut-text name ml-2"><b>{{clip.clipName|limit_title}}</b></div>
                                <div class="card-cut-text topic ml-2">{{clip.recordedVideo.topic|get_topicName}}</div>
                                <span class="date" style="display:none;">{{clip.recordedVideo.videoDate|normalize_date}}</span>
                              </div>
                            </div>
                          </a>
                        </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
    </div>
 </div>

{% if channel.owningUser == current_user.id %}
<!-- Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editModalTitle">Edit Stream Info</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form>
          <div class="modal-body">
                <h5>Name of the Stream:</h5>
                <input type="text" id="editStreamNameInput" class="form-control" value="{{stream.streamName}}" name="newStreamName" required>
                <br>
                <h5>Stream Topic:</h5>
                <select class="form-control" name="newStreamTopic" id="editChannelTopicInput" style="font-family: FontAwesome, sans-serif;" required >
                    {% for topic in topics %}
                    <option value={{topic.id}} {% if stream.topic==topic.id %} selected {% endif %}>{{topic.name}}</option>
                    {% endfor %}
                </select>
          </div>
          <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary" data-dismiss="modal" onClick="submitStreamChanges()">Save Changes</button>
          </div>
      </form>
    </div>
  </div>
</div>

{% endif %}

<div class="modal fade" id="shareModal" tabindex="-1" role="dialog" aria-labelledby="shareModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="shareModalTitle">Share a Video/Stream</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">
          <div style="margin: 0 auto;width: 99%; text-align: center;">
            <button type="button" id="FBShareBtn" class="btn shadow" style="background-color:#4267B2;color:white;" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u={{request.url}}','facebook-share-dialog','width=626,height=436');return false;">Share on Facebook</button>
            <button type="button" id="TwitterShareBtn" class="btn shadow" style="background-color:#1dcaff;color:white;" onclick="window.open('https://twitter.com/share?url={{request.url}}&text=Check out this Stream! - {{stream.streamName}}','twitter-share-dialog','width=626,height=436');return false;">Share on Twitter</button>
          </div>
        <br>
        <div class="form-group row">
            <label for="embedURLInput" class="col-sm-2 col-form-label"><b>Embed</b></label>
            <div class="col-sm-10">
                <div class="input-group mb-3">
                  <div class="input-group-prepend">
                      <button type="button" class="btn btn-primary" onclick="CopyDiv('embedURLInput')"><i class="fas fa-copy"></i></button>
                  </div>
                  <input class="form-control" id="embedURLInput" type="text" value="<iframe src='{{request.url}}?embedded=True' width=600 height=345></iframe>" readonly onClick="this.select();">
                </div>
            </div>
        </div>
        <div class="form-group row">
            <label for="linkShareInput" class="col-sm-2 col-form-label"><b>Link</b></label>
            <div class="col-sm-10">
                <div class="input-group mb-3">
                  <div class="input-group-prepend">
                      <button type="button" class="btn btn-primary" onclick="CopyDiv('linkShareInput')"><i class="fas fa-copy"></i></button>
                  </div>
                  <input class="form-control" id="linkShareInput" type="text" value="{{request.url}}" readonly onClick="this.select();">
                </div>
            </div>
        </div>
        <div class="form-group row">
            <label for="rtmpURI" class="col-sm-2 col-form-label"><b>RTMP Link</b></label>
            <div class="col-sm-10">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                          <button type="button" class="btn btn-primary" onclick="CopyDiv('rtmpURI')"><i class="fas fa-copy"></i></button>
                    </div>
                    <input class="form-control" id="rtmpURI" type="text" value="{{rtmpURI}}" readonly onClick="this.select();">
                </div>
            </div>
        </div>
      </div>
      <div class="modal-footer">

        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block scripts %}

    <script>
        var player = videojs('video', {
            autoplay: true,
            errorDisplay: false,
            liveui: true,
            liveTracker:true,
            html5:
                {
                    nativeAudioTracks: false,
                    nativeVideoTracks:false,
                    hls:
                        {
                            overrideNative: true
                        }
                }
        });


        player.ready(function() {
               this.src({
                       src: '{{streamURL}}',
                       type: 'application/x-mpegURL'
               });
       });

       player.play();
    </script>

    <script>
        $(document).ready( function () {
            monitor_vid(player);
        });
    </script>


    <script type="text/javascript" charset="utf-8">
        var conn_options = {
            'sync disconnect on unload':true
        };

        var socket = io();
    </script>

    <script>
        socket.on('connect', function() {
            socket.emit('newViewer', {data: '{{channel.channelLoc}}'});
        });
    </script>

    <script>
        socket.on('disconnect', function() {
            socket.emit('removeViewer', {data: '{{channel.channelLoc}}'});
        });
    </script>


    <script>
        window.addEventListener("beforeunload", function (e) {
            socket.emit('removeViewer', {data: '{{channel.channelLoc}}'});
            return null;
        });
    </script>

    <script type="text/javascript" charset="utf-8">
        socket.on('viewerTotalResponse', function (msg) {
            document.getElementById("currentViewers").innerHTML = msg['data'];
            var userBoxHTML = "";
            var userList = msg['userList'];
            var userListLength = userList.length;
            for (var i = 0; i < userListLength; i++) {
                userBoxHTML = userBoxHTML.concat(userList[i],'<br>');
            }
            var userListElement = document.getElementById("userList");
            userListElement.setAttribute("data-content",userBoxHTML);
        });
    </script>

    <script>
        var chatTimer;
        var chatThrottled = false;
        var chatTimeout = 2000;

        function chatThrottleDisable() {
            chatThrottled = false;
        }

        function sendChat() {
            if (chatThrottled == false) {
                text = $('#text').val();
                $('#text').val('');
                socket.emit('text', {msg: text, room: '{{channel.channelLoc}}'});
                chatThrottled = true;
                chatTimer = setTimeout(chatThrottleDisable, chatTimeout);
            }

        };

        $('#text').keypress(function(e) {
            var code = e.keyCode || e.which;
            if (code == 13) {
                sendChat();
            }
        });
    </script>

    <script>

        socket.on('message', function(data) {
            var today = new Date();
            var h = today.getHours();
            var m = (today.getMinutes() < 10? '0' : '') + today.getMinutes();
            var s = today.getSeconds();
            var message = data['msg'];
            if (data['flags'] === 'Owner') {
                $('#chat').append('<div class="chatBar-Item chat-{{channel.chatBG}} {{channel.chatAnimation}}"><div class="charBar-Item-Image"><img class="rounded" src="' + data['image'] + '" width="52px" height="52px"></div><div class="chatBar-Item-Text" style="color:{{channel.chatTextColor}};"><b>' + data['user'] + '</b> <i class="fas fa-crown"></i> ' + h + ':' + m + '<br>' + message + '</div></div>');
            } else if (data['flags'] === 'Bot')
            {
                $('#chat').append('<div class="chatBar-Item chat-{{channel.chatBG}} {{channel.chatAnimation}}"><div class="charBar-Item-Image"><img class="rounded" src="' + data['image'] + '" width="52px" height="52px"></div><div class="chatBar-Item-Text" style="color:{{channel.chatTextColor}};"><b>' + data['user'] + '</b> <i class="fas fa-robot"></i> ' + h + ':' + m + '<br>' + message + '</div></div>');
            } else {
                $('#chat').append('<div class="chatBar-Item chat-{{channel.chatBG}} {{channel.chatAnimation}}"><div class="charBar-Item-Image"><img class="rounded" src="' + data['image'] + '" width="52px" height="52px"></div><div class="chatBar-Item-Text" style="color:{{channel.chatTextColor}};"><b>' + data['user'] + '</b> ' + h + ':' + m + '<br>' + message + '</div></div>');
            }
            $('#chat').animate({ scrollTop: 1000000 }, "fast");
        });
    </script>

    <script>
        $(function () {
            $('[data-toggle="popover"]').popover()
        })
    </script>

    <!--<script>
        setInterval(function() {
          socket.emit('getViewerTotal', {data: "{{channel.channelLoc}}"} );
        },5000 );
    </script>-->

    <script>
        socket.on('connect', function() {
            socket.emit('getUpvoteTotal', {loc: '{{channel.channelLoc}}', vidType: 'stream'});
            socket.emit('getViewerTotal', {data: "{{channel.channelLoc}}"} );
        });
    </script>

    <script>
        setInterval(function() {
          socket.emit('getUpvoteTotal', {loc: '{{channel.channelLoc}}', vidType: 'stream'});
        },30000 );
    </script>

    <script type="text/javascript" charset="utf-8">
        socket.on('upvoteTotalResponse', function (msg) {
            document.getElementById("totalUpvotes").innerHTML = msg['totalUpvotes'];
            if (msg['myUpvote'] === 'True'){
                if ( document.getElementById("upVoteIcon").classList.contains('far') ) {
                    document.getElementById("upVoteIcon").classList.remove('far');
                    document.getElementById("upVoteIcon").classList.add('fas');
                }
            }
            else if (msg['myUpvote'] === 'False'){
                if ( document.getElementById("upVoteIcon").classList.contains('fas') ) {
                    document.getElementById("upVoteIcon").classList.remove('fas');
                    document.getElementById("upVoteIcon").classList.add('far');
                }
            }
        });
    </script>

    <script>
        function changeUpvote() {
            socket.emit('changeUpvote', {loc: '{{channel.channelLoc}}', vidType: 'stream'});
            socket.emit('getUpvoteTotal', {loc: '{{channel.channelLoc}}', vidType: 'stream'});
        }
    </script>

    <script>
        function toggleChat() {
            var chatbox = document.getElementById("chatside");
            if (chatbox.style.display === "none") {
                chatbox.style.display = "block";
            } else {
                chatbox.style.display = "none";
            }
        }
    </script>

    <script>
        function popoutChat() {
            MyWindows=window.open('/view/{{channel.channelLoc}}/?chatOnly=True','myWindow', 'width=500,height=850');
            var chatbox = document.getElementById("chatside");
            chatbox.style.display = "none";
        }
    </script>

    <script>
        function submitStreamChanges(){
            var newStreamNameDiv = document.getElementById("editStreamNameInput");
            var newStreamTopicDiv = document.getElementById("editChannelTopicInput");

            socket.emit('updateStreamData', {name: newStreamNameDiv.value, topic: newStreamTopicDiv.value, channel:"{{channel.channelLoc}}"});
        }
    </script>


    <script>
    //Fixes for VideoJS on Disconnect to Force a Reconnect when the readyState is stuck at 2
    function monitor_vid(vidplayer){


        videoJSObj = vidplayer;
        currentReadyState = videoJSObj.readyState();

        videoWindowState = document.getElementsByTagName('video');

        videoContainer = document.getElementById('videoContainer');
        offlineWindow = document.getElementById('offlineImage');

        onlineBadge = document.getElementById('liveIndicatorBadge');

        $.getJSON('/apiv1/channels/{{channel.channelLoc}}', function(data) {
            var channelList = data['results'][0];
            var streamIDList = channelList['stream'];

            if (streamIDList.length > 0) {
                var currentStreamID = streamIDList[0];

                videoContainer.style.display = "block";
                offlineWindow.style.display = "none";

                if (currentReadyState == 2) {
                    try {
                        videoJSObj.pause();
                        videoJSObj.currentTime(0);
                        videoJSObj.play();
                        currentReadyState = videoJSObj.readyState();
                    } catch(e) {
                        console.log("OSP tried restarting the stream but had an issue:" + e)
                    }
                } else if (currentReadyState == 0) {
                    try {
                        videoJSObj.reset();
                        videoJSObj.src('{{streamURL}}');
                        videoJSObj.pause().trigger('loadstart');
                        videoJSObj.play();
                    } catch (e) {
                        console.log("OSP tried restarting the stream but had an issue:" + e)
                    }
                }

                $.getJSON('/apiv1/streams/' + currentStreamID, function(data) {
                    var streamData = data['results'][0];
                    var currentStreamTopic = streamData['topic'];
                    var currentStreamName = streamData['streamName'];

                    var topicDiv = document.getElementById('streamMetadataTopic');
                    var nameDiv = document.getElementById('streamMetadataName');

                    var topicJSList = [];
                    {% for x in topics %}
                    topicJSList["{{x.id}}"] =  "{{x.name}}";
                    {% endfor %}


                    var nameDivHTML = '<b><i class="fas fa-video"></i> <span> ' + currentStreamName +  '</span></b>';
                    var topicDivHTML = '<b><i class="fas fa-hashtag"></i> <a href="/topics/' + currentStreamTopic + '"><span>' + topicJSList[currentStreamTopic] +  '</span></a></b>';

                    onlineBadge.className = 'float-right badge badge-danger';
                    onlineBadge.innerHTML = '<i class="fas fa-video"></i><span class="d-none d-sm-none d-md-inline"> Live</span>';

                    nameDiv.innerHTML = nameDivHTML;
                    topicDiv.innerHTML = topicDivHTML;

                });

            } else {
                try {
                    videoJSObj.pause();
                    videoJSObj.reset();
                    onlineBadge.className = 'float-right badge badge-secondary';
                    onlineBadge.innerHTML = '<i class="fas fa-video-slash"></i><span class="d-none d-sm-none d-md-inline"> Offline</span>';
                    videoContainer.style.display = "none";
                    offlineWindow.style.display = "block";
                    var currentStreamName = "No Stream";
                    var nameDiv = document.getElementById('streamMetadataName');
                    var nameDivHTML = '<span><b> ' + currentStreamName +  '</b></span>';
                    nameDiv.innerHTML = nameDivHTML;

                } catch(e) {
                    console.log("OSP tried restarting the stream but had an issue:" + e)
                }
            }
        });
        var lastVideoState = currentReadyState;
    }

    setInterval(function() {
        monitor_vid(player);
    }, 10000);
    </script>

    <script>
        function CopyDiv(divVal) {
          var copyText = document.getElementById(divVal);
          copyText.select();
          document.execCommand("copy");
        }
    </script>

    <script>
    function toggleChannelSub(chanID) {
        socket.emit('toggleChannelSubscription', { channelID: chanID });
    }
    </script>
    <script>

    socket.on('sendChanSubResults', function (msg) {
        var subButton = document.getElementById('chanSubStateButton');
        if (msg['state'] === true) {
            subButton.innerHTML = "<i class='fas fa-star'></i><span class='d-none d-sm-none d-md-inline'> Unsubscribe</span>";
            subButton.className = "btn btn-sm btn-success";
        } else {
            subButton.innerHTML = "<i class='far fa-star'></i><span class='d-none d-sm-none d-md-inline'> Subscribe</span>";
            subButton.className = "btn btn-sm btn-outline-success";
        }
      });
    </script>

    <script>
        videoListOptions = {
            valueNames: ['name', 'upvotes', "views", "length", "date"]
        };

        clipListOptions = {
            valueNames: ['name', 'upvotes', "views", "length", "date"]
        };

        var recordedVideosList = new List('recordedVideoList', videoListOptions);
        var clipList = new List('clipsList', clipListOptions);

    </script>
{% endblock %}